package com.geek.water.controller;

import com.geek.water.constant.CodeConstant;
import com.geek.water.constant.MessageConstant;
import com.geek.water.constant.RedisMessageConstant;
import com.geek.water.entity.User;
import com.geek.water.result.Result;
import com.geek.water.service.UserService;
import com.geek.water.utils.JwtHelper;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * @author yangwenqi
 * @decs TODO
 * @date 2025/8/12
 */

@RestController
@RequestMapping("/app/member")
@RequiredArgsConstructor
@Slf4j
public class MemberController {

    private final StringRedisTemplate redisTemplate;
    private final UserService userService;

    @ApiOperation("手机验证码登录")
    @PostMapping("/login")
    public Result login(@RequestBody Map<String, String> loginParam) {
        log.info("收到登录请求，参数: {}", loginParam);

        String phone = loginParam.get("telephone");
        String validateCode = loginParam.get("validateCode");

        // 参数验证
        if (phone == null || validateCode == null) {
            log.warn("登录参数不完整，手机号: {}, 验证码: {}", phone, validateCode);
            return new Result(CodeConstant.FAIL, MessageConstant.PHONE_NUMBER_AND_VALIDATE_CODE_CANNOT_BE_EMPTY);
        }

        // 第一步：验证数据库中是否存在该用户
        log.info("开始验证用户是否存在，手机号: {}", phone);
        User user = userService.findByMobile(phone);
        if (user == null) {
            log.warn("用户不存在，手机号: {}", phone);
            return new Result(CodeConstant.FAIL, MessageConstant.USER_NOT_EXIST);
        }
        log.info("用户验证成功，用户ID: {}, 用户名: {}", user.getId(), user.getUsername());

        // 第二步：验证验证码是否正确
        String redisKey = phone + RedisMessageConstant.SENDTYPE_LOGIN + "_" + validateCode;
        log.info("开始验证验证码，Redis key: {}", redisKey);
        String storedCode = redisTemplate.opsForValue().get(redisKey);

        if (storedCode == null || !storedCode.equals(validateCode)) {
            log.warn("验证码验证失败，手机号: {}, 输入验证码: {}, 存储验证码: {}", phone, validateCode, storedCode);
            return new Result(CodeConstant.FAIL, MessageConstant.VALIDATE_CODE_ERROR_OR_EXPIRED);
        }
        log.info("验证码验证成功，手机号: {}", phone);

        // 验证成功，生成JWT token
        String token = JwtHelper.createToken(user.getId().longValue(), user.getUsername());
        log.info("生成JWT token成功，用户ID: {}", user.getId());

        // 清除验证码
        redisTemplate.delete(redisKey);
        log.info("已清除Redis中的验证码");

        // 更新最后登录时间
        userService.updateLastLoginTime(user.getId());

        // 返回登录成功信息
        Map<String, Object> result = new HashMap<>();
        result.put("token", token);
        result.put("user", user);

        log.info("用户登录成功，用户ID: {}, 手机号: {}", user.getId(), phone);
        return new Result(CodeConstant.SUCCESS, MessageConstant.LOGIN_SUCCESS, result);
    }
}

